const path = require('path');
const router = require('koa-router')();
const model = require('../../models/user');
const timestring = require('../../utils/lib/time').timestring;
const { v4: uuidv4} = require('uuid');
const { redis } = require('../../config/env');
const RedisStore = require('koa-redis')(redis);

const dao = require('../../dao/' + path.basename(__dirname));

router.post('/', async function (ctx, next) {
    const body = ctx.request.body;          //获取表单登录用户名与密码
    if (!body.account || !body.password) {
        ctx.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: '缺少必须字段（账号/密码）!'
        }
        return
    }

    let user, loginType
    if (/^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,5})$/.test(body.account)) {
        user = await model.findOne({
            where: {
                email: body.account,
            }
        })
        loginType = 1
    } else {
        user = await model.findOne({
            where: {
                username: body.account,
            }
        })
        loginType = 2
    }
    if (!user) {             //用户名不存在
        console.log('用户名不存在!');
        ctx.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: '用户名不存在!'
        }
        return
    }
    if (user.password !== body.password) {
        console.log('密码错误');
        ctx.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: "密码错误!"
        }
        return
    }
    ctx.session['user'] = user.username;
    ctx.session['logged'] = true;
    let session_id = uuidv4(user.id);
    let session_is_exist = await RedisStore.get(session_id);        //判断是否有相同session_id存在
    if (session_is_exist) {
        await RedisStore.destroy(session_id);
    }
    const result0 = await RedisStore.set(session_id, ctx.session, 24 * 60 * 60 * 1000);
    console.log('登录成功!');
    let time = timestring();
    if (loginType === 1) {
        dao.update({ last_login_at: time, session_id: session_id }, {            //记录最近登录时间
            email: body.account
        });
    } else if (loginType === 2) {
        dao.update({ last_login_at: time, session_id: session_id }, {            //记录最近登录时间
            username: body.account
        });
    }

    ctx.cookies.set('session_id', uuidv4(user.id), {
        maxAge: 24 * 60 * 60 * 1000,
    })
    ctx.session.logged = true;
    ctx.status = 200;
    ctx.type = 'json/application';
    ctx.response.body = {
        'statusCode': 200,
        'user': user,
    };
    await next();
});

module.exports = router.routes();
